<template>
  <!-- 搜索工作栏 -->
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="问卷名称" prop="paperName">
        <el-input
          v-model.tirm="queryParams.paperName"
          placeholder="请输入问卷名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="问卷状态" prop="paperStatus">
        <el-select
          v-model="queryParams.paperStatus"
          placeholder="请选择问卷状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in paperStatusList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button type="primary" @click="openForm('create')">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list">
      <el-table-column
        label="问卷名称"
        align="center"
        prop="paperName"
        min-width="150"
        show-overflow-tooltip
      />
      <el-table-column label="问卷状态" align="center" prop="paperStatus" min-width="100">
        <template #default="scope">
          {{ getLabel(paperStatusList, scope.row.paperStatus) }}
        </template>
      </el-table-column>
      <el-table-column label="单选题数量" align="center" prop="singleChoiceTotal" min-width="100" />
      <el-table-column
        label="多选题数量"
        align="center"
        prop="multipleChoiceTotal"
        min-width="100"
      />
      <el-table-column label="判断题数量" align="center" prop="judgeTotal" min-width="100" />
      <el-table-column label="简答题数量" align="center" prop="shortAnswerTotal" min-width="100" />
      <el-table-column label="问卷密码" align="center" prop="id" min-width="100" />
      <el-table-column label="操作" align="center" fixed="right" width="300">
        <template #default="scope">
          <el-button link type="success" @click="toPreviewPaper(scope.row)"> 问卷预览 </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            :disabled="scope.row.paperStatus === 2"
          >
            编辑
          </el-button>
          <el-button
            link
            type="success"
            @click="handlePublish(scope.row.id)"
            v-if="scope.row.paperStatus === 1"
          >
            发布
          </el-button>
          <el-button
            link
            type="warning"
            @click="handleShare(scope.row)"
            v-if="scope.row.paperStatus === 2"
          >
            分享
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            :disabled="scope.row.paperStatus === 2"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <PaperForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts" name="Paper">
import PaperForm from './PaperForm.vue'
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const router = useRouter() // 路由对象
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  paperName: null,
  paperStatus: null
})
const queryFormRef = ref() // 搜索的表单

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const saved = window.localStorage.getItem('paperList')
    const listData = saved ? JSON.parse(saved) : []
    list.value =
      listData.length > 0
        ? listData
        : [
            {
              id: '2299287188',
              paperName: '测试问卷1',
              paperStatus: 1,
              singleChoiceTotal: 1,
              multipleChoiceTotal: 1,
              judgeTotal: 1,
              shortAnswerTotal: 1
            },
            {
              id: '4322404096',
              paperName: '测试问卷2',
              paperStatus: 2,
              singleChoiceTotal: 1,
              multipleChoiceTotal: 1,
              judgeTotal: 1,
              shortAnswerTotal: 1
            }
          ]
    // 把题目存到store
    window.localStorage.setItem('paperList', JSON.stringify(list.value))
    if (queryParams.paperName)
      list.value = list.value.filter((item) => item.paperName == queryParams.paperName)
    if (queryParams.paperStatus)
      list.value = list.value.filter((item) => item.paperStatus == queryParams.paperStatus)
    total.value = list.value.length
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    list.value = list.value.filter((item) => item.id != id)

    // 把题目存到store
    window.localStorage.setItem('paperList', JSON.stringify(list.value))
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

// 发布
const handlePublish = async (id: number) => {
  try {
    // 删除的二次确认
    await message.confirm('确定要发布该问卷吗?')
    // 发起删除
    list.value.map((item) => {
      if (item.id == id) item.paperStatus = 2
    })

    // 把题目存到store
    window.localStorage.setItem('paperList', JSON.stringify(list.value))
    message.success('发布成功')
    // 刷新列表
    await getList()
  } catch {}
}

// 分享
const handleShare = async (row: Object) => {
  const queryParams = new URLSearchParams()
  for (const key in row) {
    if (row.hasOwnProperty(key)) {
      queryParams.set(key, row[key])
      queryParams.set('openType', '3')
    }
  }

  // 完整的URL，包括基础URL和查询字符串
  const url = `${window.location.origin}/preview-paper?${queryParams}`

  try {
    await navigator.clipboard.writeText(url)
    message.success('链接已复制到剪贴板！')
  } catch (err) {
    // 兼容降级：创建临时输入框复制
    const input = document.createElement('input')
    input.value = url
    document.body.appendChild(input)
    input.select()
    document.execCommand('copy')
    document.body.removeChild(input)
    message.success('链接已复制到剪贴板！')
  }
}

// 问卷预览
const toPreviewPaper = (row: Object) => {
  const queryParams = new URLSearchParams()
  for (const key in row) {
    if (row.hasOwnProperty(key)) {
      queryParams.set(key, row[key])
      queryParams.set('openType', '1')
    }
  }

  // 完整的URL，包括基础URL和查询字符串
  const url = `${window.location.origin}/preview-paper?${queryParams}`

  // 在新窗口中打开URL
  window.open(url, '_blank')
}

// 问卷状态
const paperStatusList = reactive([
  { value: 1, label: '未发布' },
  { value: 2, label: '已发布' }
])

const getLabel = (list: Array<any>, value: any) => {
  const dictLabel = ref('')
  list.forEach((dict: any) => {
    if (dict.value == value) {
      dictLabel.value = dict.label
    }
  })
  return dictLabel.value
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
